/*
 * Copyright (c) 2011 learemraf@gmail.com
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
package com.googlecode.frank.driver.impl;

import static com.google.common.base.Preconditions.checkArgument;

import java.util.Arrays;
import java.util.List;

import org.apache.commons.lang.NotImplementedException;
import org.apache.commons.lang.time.StopWatch;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.googlecode.frank.driver.FrankDriver;
import com.googlecode.frank.driver.Operation;
import com.googlecode.frank.driver.Response;

/**
 * @author farmerl
 */
public class FrankDriverImpl implements FrankDriver{

    private static final Logger LOG = LoggerFactory.getLogger(FrankDriverImpl.class);

    public void touch(String query) {
        List<String> touch = franklyMap(query, "touch");
        checkArgument(touch.isEmpty(), "Could not find anything matching %s", query);
    }

    public boolean elementExists(String query) {
        List<String> matches = franklyMap(query, "accessibilityLabel");
        return !matches.isEmpty();
    }

    public boolean checkElementExist(String query) {
        return elementExists(query);
    }

    public boolean checkElementDoesNotExist(String query) {
        return elementExists(query);
    }

    public boolean viewWithMarkExists(String expectedMark) {
        return elementExists("view marked:'#{"+expectedMark+"}'");
    }

    public boolean checkViewWithMarkExists(String expectedMark) {
        return checkElementExist("view marked:'#{"+expectedMark+"}'");
    }

    public boolean elementExistsAndIsNotHidden(String query) {
        List<String> isHidden = franklyMap(query, "isHidden");
        for(String element : isHidden) {
            if(isHidden.equals("true")) {
                isHidden.remove(element);
            }
        }
        return !isHidden.isEmpty();
    }

    public List<String> applicationExecute(String methodName, String... args) {
        Operation operation = new Operation();
        operation.setMethod_name(methodName);
        operation.setArguments(Arrays.asList(args));

        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        Response response = postToUispecServer("app_exec", operation);
        stopWatch.stop();
        LOG.debug("MAP applying {} with args {} to Application delegate took {}",
                new Object[]{methodName, args, stopWatch.getTime()});
        if(!response.getOutcome().equalsIgnoreCase("SUCCESS")) {
            throw new RuntimeException(methodName + " failed because: "
                    +response.getReason()+ " details "+ response.getDetail());
        }
        return response.getResults();
    }

    public List<String> franklyMap(String query, String methodName, String... args) {
        Operation operation = new Operation();
        operation.setMethod_name(methodName);
        operation.setArguments(Arrays.asList(args));

        Response response = postToUispecServer("app_exec", operation);

        if(!response.getOutcome().equalsIgnoreCase("SUCCESS")) {
            throw new RuntimeException(methodName+" : "+query+" failed because: "
                    +response.getReason()+ " details "+ response.getDetail());
        }
        return response.getResults();
    }

    public void franklyDump() {
        Response response = getToUispecServer("dump");
        LOG.info(response.toString());
    }

    public boolean franklyOrientedPortrait() {
        return "portrait".equals(franklyCurrentOrientation());
    }

    public boolean franklyOrientedLandscape() {
        return "landscape".equals(franklyCurrentOrientation());
    }

    public String franklyCurrentOrientation() {
        Response response = getToUispecServer("orientation");
        LOG.debug("Response for franklyCurrentOrientation : {}", response.toString());
        //TODO : See whats coming back as frank cucumber code is looking for 'orientation'
        return response.getResults().get(0);
    }

    public boolean franklyIsAccessibilityEnabled() {
        Response response = getToUispecServer("accessibility_check");
        //TODO : See whats coming back as frank cucumber code is looking for 'accessibility_check'
        return response.getResults().get(0).equalsIgnoreCase("true");
    }

    public void waitForFrankToComeUp() {
        throw new NotImplementedException();
    }

    public boolean franklyPing() {
        try {
            getToUispecServer("");
            return true;
        } catch (Exception ex) {
            return false;
        }
    }

    public Response postToUispecServer(String verb, Operation operation) {
        throw new NotImplementedException();
    }

    public Response getToUispecServer(String verb) {
        throw new NotImplementedException();
    }

    public String frankUrlFor(String verb) {
        throw new NotImplementedException();
    }
}
